package com.NetWork.lesson3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;


public class TalkSend implements Runnable{
    DatagramSocket socket = null;
    BufferedReader br = null;
    private String toIp;
    private int toPort;
    private int fromPort;

    public TalkSend(String toIp, int toPort) {
        this.toIp = toIp;
        this.toPort = toPort;

        try {
            socket = new DatagramSocket(this.fromPort);
            br = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {
        while(true) {//循环发送
            try {
                String data = br.readLine();//一行一行读
                byte[] buffer = data.getBytes();//必须转字节
                DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length, new InetSocketAddress(this.toIp,this.toPort));
                socket.send(packet);
                if (data.equals("q")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();

    }
}

    